package org.dbstar.scheduler.ldap;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.dbstar.scheduler.beans.OperateType;
import org.dbstar.scheduler.beans.User;
import org.dbstar.scheduler.control.AuthorityController;
import org.dbstar.scheduler.control.OperateController;
import org.dbstar.scheduler.control.exception.DaoException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;


/**
 * 用户认证成功后的处理
 * 
 * @author 代波
 * @since 1.0.0
 * @version 1.0.0
 * @date 2012-6-5
 */
public class SchedulerAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
	private final AuthorityController authorityController;
	private final OperateController operateController;

	public SchedulerAuthenticationSuccessHandler(AuthorityController authorityController,
			OperateController operateController) {
		super();
		this.authorityController = authorityController;
		this.operateController = operateController;
	}

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		super.onAuthenticationSuccess(request, response, authentication);
		try {
			// 更新用户授权
			User user = buildUser(authentication);
			authorityController.update(user);
			operateController.operate(user.getUsername(), OperateType.login_success,
					StringUtils.join(user.getAuthorities(), ','));
		} catch (DaoException e) {
			throw new ServletException(e);
		}
	}

	private static User buildUser(Authentication authentication) {
		User user = new User();
		user.setUsername(authentication.getName());
		user.setDisplayName(((SchedulerUserDetails) authentication.getPrincipal()).getDisplayName());
		for (GrantedAuthority authority : authentication.getAuthorities()) {
			user.addAuthority(authority.getAuthority());
		}
		return user;

	}
}
